package dao;

import vo.Message;
import vo.Private;
import vo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class Privatedao {
    public void addMessage(Private pri) throws SQLException {
        Connection conn= Base.getConnection();
        String sql = "INSERT INTO private(username,privatename,message,time) VALUES (?,?,?,?)";
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1, pri.getUsername());
        preparedStatement.setString(2, pri.getPrivatename());
        preparedStatement.setString(3, pri.getMessage());
        preparedStatement.setTimestamp(4, new java.sql.Timestamp(pri.getTime().getTime()));
        preparedStatement.executeUpdate();
    }
    public List<Private> getMessages(String username) throws SQLException {
        Connection conn = Base.getConnection();
        List<Private> privates = new ArrayList<>();
        String sql = "SELECT * FROM private where username=?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, username);
        ResultSet set = pst.executeQuery();
        while (set.next()) {
            Private pri=new Private();
            pri.setUsername(set.getString(1));
            pri.setPrivatename(set.getString(2));
            pri.setMessage(set.getString(3));
            pri.setTime(set.getDate(4));
            privates.add(pri);
        }
        Base.close(conn,pst,set);
        return privates;
    }
    public List<Private> getOwnmessages(String username)throws SQLException{
        Connection conn = Base.getConnection();
        List<Private> owners = new ArrayList<>();
        String sql = "SELECT * FROM private where privatename=?";
        PreparedStatement pst = conn.prepareStatement(sql);
        pst.setString(1, username);
        ResultSet set = pst.executeQuery();
        while (set.next()) {
            Private own=new Private();
            own.setUsername(set.getString(1));
            own.setPrivatename(set.getString(2));
            own.setMessage(set.getString(3));
            own.setTime(set.getDate(4));
            owners.add(own);
        }
        Base.close(conn,pst,set);
        return owners;
    }
}

